define(function (require, exports, module) {
    require('./css/style.css')
    const streetStyle = require('../../../map/mapbox/style/street.js').onload();
    const imageStyle = require('../../../map/mapbox/style/image.js').onload();
    const drawStyle = require('../../../map/mapbox/style/draw.js').onload();

    const {CutPolygon} = require('../../../map/mapbox/modes/CutPolygon.js').onload();
    const {DirectSelect} = require('../../../map/mapbox/modes/DirectSelect.js').onload();
    const {SimpleSelect} = require('../../../map/mapbox/modes/SimpleSelect.js').onload();
    const {DrawPassing, DrawPassingEvents} = require('../../../map/mapbox/modes/DrawPassing.js').onload();
    const {PolygonStickTo, PolygonStickToEvents} = require('../../../map/mapbox/modes/PolygonStickTo.js').onload();
    const {DrawCenter, DrawCenterEvents} = require('../../../map/mapbox/modes/DrawCenter.js').onload();
    const Compare = require('../../../map/mapbox/compare/compare.js').onload();
    const Constants = require('../../../map/mapbox/modes/utils/constants.js').onload();
    const ElMessage = window.ELEMENT.Message
    const ElMessageBox = window.ELEMENT.MessageBox

    function onload() {
        // 当前的吸附点ID
        const currentStickToId = "current-stick-to"
        // 自身网格图层和数据源共用ID
        const selfId = "grid-self"
        // 其他网格图层和数据源共用ID
        const othersId = "grid-others"
        // 坐标点集合图层和数据源共用ID
        const centersId = "grid-centers"
        // 多边形吸附绘制模式
        const mode = "polygon_stick_to"

        return {
            template: require('./Widget.html'),
            name: 'DrawGrid',
            props: {
                title: {
                    type: String,
                    required: false,
                    default: ""
                },
                // 类型：部门：dept、乡镇街道：street、社区村屯：community
                dataType: {
                    type: String,
                    required: true
                },
                // 数据ID
                dataId: {
                    type: Number,
                    required: true
                },
                // 数据权限
                dataPermission: {
                    type: Array,
                    required: false,
                    default: () => []
                }
            },
            mounted() {
            },
            created() {
                const mapConfig = window.config.map
                this.mapCenter = mapConfig.center
                this.minZoom = mapConfig.minZoom
                this.maxZoom = mapConfig.maxZoom
            },
            data() {
                return {
                    minZoom: 9,
                    maxZoom: 9,
                    // A图
                    mapA: undefined,
                    // B图
                    mapB: undefined,
                    // A绘制控件
                    drawA: undefined,
                    // B绘制控件
                    drawB: undefined,
                    // 自身特征（多面）
                    selfFeature: undefined,
                    // 其他特征集合（多面的集合）
                    otherFeatureCollection: undefined,
                    open: false,
                    // 地图默认中心点
                    mapCenter: [124.54560959511093, 47.69965016453599],
                    // 正在绘制内环
                    drawingCut: false,
                    // 绘制状态：
                    // 0：正在绘制：（任何种类的绘制都试用）
                    //    （1）绘制网格：灭
                    //    （2）绘制飞地：灭
                    //    （3）绘制内环：灭
                    //    （4）保存绘制：灭
                    //    （5）编辑网格：灭
                    //    （6）删除飞地：灭
                    //    （7）删除内环：灭
                    //    （8）删除网格：灭
                    // 1：绘制完毕，但未保存：（任何种类的绘制都试用）
                    //    （1）绘制网格：灭
                    //    （2）绘制飞地：灭
                    //    （3）绘制内环：灭
                    //    （4）保存绘制：亮
                    //    （5）编辑网格：灭
                    //    （6）删除飞地：灭
                    //    （7）删除内环：灭
                    //    （8）删除网格：灭
                    // 2: 没有主网格：
                    //    （1）绘制网格：亮
                    //    （2）绘制飞地：灭
                    //    （3）绘制内环：灭
                    //    （4）保存绘制：灭
                    //    （5）编辑网格：灭
                    //    （6）删除飞地：灭
                    //    （7）删除内环：灭
                    //    （8）删除网格：灭
                    // 3: 已有主网格：
                    //    （1）绘制网格：灭
                    //    （2）绘制飞地：亮
                    //    （3）绘制内环：亮
                    //    （4）保存绘制：灭
                    //    （5）编辑网格：亮
                    //    （6）删除飞地：亮
                    //    （7）删除内环：亮
                    //    （8）删除网格：亮
                    drawStatus: -1,
                    // 尚未绘制父网格
                    noParent: false,
                }
            },
            methods: {
                toDraw() {
                    this.open = true
                    this.$nextTick(() => {
                        this.initMap()
                    })
                },
                /**
                 * 切换为多边形吸附绘制模式
                 * @param draw 绘制控件
                 * @param eventType 绘制后触发的事件类型
                 * @param coordinatesArr 已绘制的点位
                 */
                changePolygonStickToMode(draw, eventType, coordinatesArr) {
                    draw.changeMode(mode, {
                        eventType,
                        coordinatesArr,
                        self: this.selfFeature && this.selfFeature.geometry.type === Constants.geojsonTypes.MULTI_POLYGON ? this.selfFeature : null,
                        others: this.otherFeatureCollection
                    })
                },
                // 初始化地图
                initMap() {
                    this.noParent = false
                    const before = this.addMap('before', streetStyle)
                    // const before = addMap('before', 'mapbox://styles/mapbox/streets-v11')
                    this.mapA = before.map
                    this.drawA = before.draw
                    const after = this.addMap('after', imageStyle)
                    // const after = this.addMap('after', 'mapbox://styles/mapbox/satellite-streets-v11')
                    this.mapB = after.map
                    this.drawB = after.draw

                    this.mapA.on(PolygonStickToEvents.UPDATE_POINT_B, ({coordinatesArr}) => {
                        this.drawB.deleteAll()
                        this.changePolygonStickToMode(this.drawB, PolygonStickToEvents.UPDATE_POINT_A, coordinatesArr)
                    })

                    this.mapB.on(PolygonStickToEvents.UPDATE_POINT_A, ({coordinatesArr}) => {
                        this.drawA.deleteAll()
                        this.changePolygonStickToMode(this.drawA, PolygonStickToEvents.UPDATE_POINT_B, coordinatesArr)
                    })

                    this.mapA.on(DrawCenterEvents.UPDATE_POINT_CENTER, ({features}) => {
                        const feature = features[0];
                        const geometry = feature.geometry;

                        $.ajax({
                            url: alluse.bigcenter + '/gis/' + this.dataType + '/update-center/' + this.dataId,
                            contentType: 'application/json;charset=utf-8',
                            type: 'POST',
                            data: JSON.stringify(geometry),
                            success: res => {
                                if (res.code === 200) {
                                    if (this.selfFeature && this.selfFeature.geometry.type === Constants.geojsonTypes.POINT) {
                                        this.selfFeature = {
                                            id: this.selfFeature.id,
                                            type: "Feature",
                                            properties: this.selfFeature.properties,
                                            geometry: geometry
                                        }
                                        this.mapA.getSource(selfId).setData(this.selfFeature)
                                        this.mapB.getSource(selfId).setData(this.selfFeature)
                                    }
                                    this.drawA.delete(feature.id)
                                    this.drawStatus = 3
                                    this.drawB.changeMode(Constants.modes.SIMPLE_SELECT)
                                    ElMessage.success('标记中心坐标成功！')

                                    this.initGridData(this.mapA, false)
                                    this.initGridData(this.mapB, false)
                                }
                            }
                        })
                    })

                    this.mapB.on(DrawCenterEvents.UPDATE_POINT_CENTER, ({features}) => {
                        const feature = features[0];
                        const geometry = feature.geometry;

                        $.ajax({
                            url: alluse.bigcenter + '/gis/' + this.dataType + '/update-center/' + this.dataId,
                            contentType: 'application/json;charset=utf-8',
                            type: 'POST',
                            data: JSON.stringify(geometry),
                            success: res => {
                                if (res.code === 200) {
                                    if (this.selfFeature && this.selfFeature.geometry.type === Constants.geojsonTypes.POINT) {
                                        this.selfFeature = {
                                            id: this.selfFeature.id,
                                            type: "Feature",
                                            properties: this.selfFeature.properties,
                                            geometry: geometry
                                        }
                                        this.mapA.getSource(selfId).setData(this.selfFeature)
                                        this.mapB.getSource(selfId).setData(this.selfFeature)
                                    }
                                    this.drawB.delete(feature.id)
                                    this.drawStatus = 3
                                    this.drawA.changeMode(Constants.modes.SIMPLE_SELECT)
                                    ElMessage.success('标记中心坐标成功！')

                                    this.initGridData(this.mapA, false)
                                    this.initGridData(this.mapB, false)
                                }
                            }
                        })
                    })

                    this.syncDraw(this.mapA, this.drawB)
                    this.syncDraw(this.mapB, this.drawA)
                    new Compare(this.mapA, this.mapB, '#comparison-container', {});
                },
                /**
                 * 创建地图
                 * @param container 容器ID
                 * @param style     样式
                 * @returns {{draw, map: mapboxgl.Map}}
                 */
                addMap(container, style) {
                    const map = new mapboxgl.Map({
                        accessToken: "pk.eyJ1IjoicGF1bGFuZGNvZGUiLCJhIjoiY2txdm94bmtmMGdsaDJvcGFia2N4M2ZydiJ9.wc0YPacoNAtaTrNCoZd8Fg",
                        container: container,
                        style: style,
                        center: this.mapCenter,
                        minZoom: this.minZoom,
                        maxZoom: this.maxZoom,
                        zoom: 12
                    })
                    map.doubleClickZoom.disable();
                    // 指南针控件
                    map.addControl(new mapboxGlControls.CompassControl(), 'bottom-right')
                    // 语言控件
                    map.addControl(new mapboxGlControls.LanguageControl({language: 'zh'}))
                    // 绘图控件
                    const draw = new MapboxDraw({
                        displayControlsDefault: false,
                        styles: drawStyle,
                        modes: Object.assign(MapboxDraw.modes, {
                            polygon_stick_to: PolygonStickTo,
                            cut_polygon: CutPolygon,
                            passing_mode_polygon: DrawPassing(
                                MapboxDraw.modes.draw_polygon
                            ),
                            simple_select: SimpleSelect,
                            direct_select: DirectSelect,
                            draw_center: DrawCenter
                        })
                    })
                    map.addControl(draw)
                    map.on('load', () => {
                        this.initGridLayer(map)
                    })
                    return {
                        map,
                        draw
                    }
                },
                /**
                 * 同步地图绘制
                 * @param mapA  地图A
                 * @param drawB 绘制B
                 */
                syncDraw(mapA, drawB) {
                    mapA.on(DrawPassingEvents.UPDATE_CUT_FINISH, (e) => {
                        const feature = e.features[0]
                        drawB.deleteAll()
                        drawB.add(feature)
                        drawB.changeMode(Constants.modes.SIMPLE_SELECT, {featureIds: [feature.id]})
                        this.drawStatus = 1
                    })

                    mapA.on(PolygonStickToEvents.CREATE, (e) => {

                        const feature = e.features[0];
                        drawB.deleteAll()
                        drawB.add(feature)
                        drawB.changeMode(Constants.modes.SIMPLE_SELECT, {featureIds: [feature.id]})
                        this.drawStatus = 1
                    })
                    mapA.on(PolygonStickToEvents.UPDATE, (e) => {
                        const feature = e.features[0];
                        drawB.deleteAll()
                        drawB.add(feature)
                        drawB.changeMode(Constants.modes.SIMPLE_SELECT, {featureIds: [feature.id]})
                        this.drawStatus = 1
                    })
                },
                // 标记中心坐标
                setCenter() {
                    this.drawStatus = 0
                    this.drawA.changeMode("draw_center")
                    this.drawB.changeMode("draw_center")
                },
                // 绘制主网格
                drawMain() {
                    this.drawStatus = 0
                    this.changePolygonStickToMode(this.drawA, PolygonStickToEvents.UPDATE_POINT_B)
                    this.changePolygonStickToMode(this.drawB, PolygonStickToEvents.UPDATE_POINT_A)
                },
                // 绘制飞地
                drawSub() {
                    this.drawStatus = 0
                    this.changePolygonStickToMode(this.drawA, PolygonStickToEvents.UPDATE_POINT_B)
                    this.changePolygonStickToMode(this.drawB, PolygonStickToEvents.UPDATE_POINT_A)
                },
                // 绘制内环
                cutSub() {
                    this.drawStatus = 0
                    this.drawingCut = true

                    this.mapA.getSource(selfId).setData({
                        type: "FeatureCollection",
                        features: []
                    })

                    this.drawA.changeMode(Constants.modes.SIMPLE_SELECT, {featureIds: this.drawA.add(this.selfFeature)})
                    this.drawA.changeMode('cut_polygon')

                    this.mapB.getSource(selfId).setData({
                        type: "FeatureCollection",
                        features: []
                    })
                    this.drawB.changeMode(Constants.modes.SIMPLE_SELECT, {featureIds: this.drawB.add(this.selfFeature)})
                    this.drawB.changeMode('cut_polygon')
                },
                // 保存绘制
                saveDraw() {
                    let coordinates
                    const geometry = this.drawA.getAll().features[0].geometry;
                    if (this.drawingCut) {
                        // 绘制内环，直接返回最终的多面
                        if (geometry.type === Constants.geojsonTypes.MULTI_POLYGON) {
                            // 有飞地时
                            coordinates = geometry.coordinates
                        } else {
                            // 没有飞地时
                            coordinates = [geometry.coordinates]
                        }
                    } else {
                        if (this.selfFeature && this.selfFeature.geometry.type === Constants.geojsonTypes.MULTI_POLYGON) {
                            // 绘制飞地
                            coordinates = this.selfFeature.geometry.coordinates
                        } else {
                            // 绘制主网格
                            coordinates = []
                        }
                        coordinates.push(geometry.coordinates)
                    }
                    const currentGrid = {
                        type: "MultiPolygon",
                        coordinates: coordinates
                    };

                    if (this.checkDifference(currentGrid.coordinates)) {
                        if (this.drawingCut) {
                            this.drawingCut = false
                        }
                        $.ajax({
                            url: alluse.bigcenter + '/gis/' + this.dataType + '/update-area/' + this.dataId,
                            contentType: 'application/json;charset=utf-8',
                            type: 'POST',
                            data: JSON.stringify(currentGrid),
                            success: res => {
                                if (res.code === 200) {
                                    const data = res.data
                                    this.selfFeature = {
                                        id: res.data.id,
                                        type: "Feature",
                                        properties: {
                                            id: data.id,
                                            name: data.name,
                                            type: "self"
                                        },
                                        geometry: currentGrid
                                    }
                                    this.drawA.deleteAll()
                                    this.drawB.deleteAll()
                                    this.mapA.getSource(selfId).setData(this.selfFeature)
                                    this.mapB.getSource(selfId).setData(this.selfFeature)
                                    this.drawStatus = 3
                                    ElMessage.success('保存绘制成功！')
                                }
                            }
                        })
                    } else {
                        if (!this.drawingCut && this.selfFeature && this.selfFeature.geometry.type === Constants.geojsonTypes.MULTI_POLYGON) {
                            // 绘制飞地
                            this.selfFeature.geometry.coordinates.pop()
                        }
                    }
                },
                checkDifference(coordinates) {
                    // const self = turf.multiPolygon(coordinates)
                    // const selfArea = turf.area(self);
                    // for (const otherFeature of this.otherFeatureCollection.features) {
                    //     const other = turf.multiPolygon(otherFeature.geometry.coordinates)
                    //     const difference = turf.difference(self, other);
                    //     if (otherFeature.properties.type === 'parent') {
                    //         if (difference && turf.area(difference) > 5) {
                    //             ElMessage.error('不能在父网格之外绘制网格! ')
                    //             return false
                    //         }
                    //     } else {
                    //         if (difference && selfArea - turf.area(difference) > 5) {
                    //             ElMessage.error('不能在同级网格之上绘制网格! ')
                    //             return false
                    //         }
                    //     }
                    // }
                    return true
                },
                // 编辑网格
                editMain() {
                    this.drawStatus = 1
                    this.drawingCut = true
                    this.mapA.getSource(selfId).setData({
                        type: "FeatureCollection",
                        features: []
                    })
                    this.mapB.getSource(selfId).setData({
                        type: "FeatureCollection",
                        features: []
                    })

                    this.drawA.deleteAll()
                    this.drawB.deleteAll()

                    this.drawA.add(this.selfFeature)
                    this.drawB.add(this.selfFeature)

                    this.drawA.changeMode(Constants.modes.SIMPLE_SELECT, {featureIds: [this.selfFeature.id]})
                    this.drawB.changeMode(Constants.modes.SIMPLE_SELECT, {featureIds: [this.selfFeature.id]})
                },
                // 删除飞地
                delSub() {
                    const coordinates = this.selfFeature.geometry.coordinates;
                    if (coordinates.length === 1) {
                        ElMessage.error("当前网格没有飞地！")
                    } else {
                        ElMessageBox.confirm('确认要删除当前网格下的所有飞地吗？', '删除飞地', {
                            confirmButtonText: '确认',
                            cancelButtonText: '取消',
                            type: 'warning',
                        }).then(() => {
                            $.ajax({
                                url: alluse.bigcenter + '/gis/' + this.dataType + '/update-area/' + this.dataId,
                                contentType: 'application/json;charset=utf-8',
                                type: 'POST',
                                data: JSON.stringify({
                                    type: "MultiPolygon",
                                    coordinates: [coordinates[0]]
                                }),
                                success: res => {
                                    if (res.code === 200) {
                                        this.selfFeature.geometry.coordinates = [coordinates[0]]
                                        this.mapA.getSource(selfId).setData(this.selfFeature)
                                        this.mapB.getSource(selfId).setData(this.selfFeature)
                                        ElMessage({
                                            type: 'success',
                                            message: "删除飞地成功！",
                                        })
                                    }
                                }
                            })
                        })
                    }
                },
                // 删除内环
                delCut() {
                    ElMessageBox.confirm('确认要删除当前网格下的所有内环吗？', '删除内环', {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }).then(() => {
                        const coordinates4 = this.selfFeature.geometry.coordinates;
                        const newCoordinates = []
                        coordinates4.forEach(coordinates3 => {
                            newCoordinates.push([coordinates3[0]])
                        })

                        $.ajax({
                            url: alluse.bigcenter + '/gis/' + this.dataType + '/update-area/' + this.dataId,
                            contentType: 'application/json;charset=utf-8',
                            type: 'POST',
                            data: JSON.stringify({
                                type: "MultiPolygon",
                                coordinates: newCoordinates
                            }),
                            success: res => {
                                if (res.code === 200) {
                                    this.selfFeature.geometry.coordinates = newCoordinates
                                    this.mapA.getSource(selfId).setData(this.selfFeature)
                                    this.mapB.getSource(selfId).setData(this.selfFeature)
                                    ElMessage({
                                        type: 'success',
                                        message: "删除内环成功！",
                                    })
                                }
                            }
                        })
                    })
                },
                // 删除网格
                delDraw() {
                    ElMessageBox.confirm('确认要删除整个网格吗？', '删除网格', {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }).then(() => {
                        $.get(alluse.bigcenter + '/gis/' + this.dataType + '/clear-area/' + this.dataId, res => {
                            this.drawStatus = 2
                            this.selfFeature = {
                                id: this.selfFeature.id,
                                type: "Feature",
                                properties: this.selfFeature.properties,
                                geometry: {
                                    type: "Point",
                                    // 写死，实际该数据没用到
                                    coordinates: this.mapCenter
                                }
                            }
                            this.mapA.getSource(selfId).setData(this.selfFeature.geometry)
                            this.mapB.getSource(selfId).setData(this.selfFeature.geometry)
                            ElMessage({
                                type: 'success',
                                message: "删除网格成功！",
                            })
                        })
                    })
                },
                // 初始化网格图层
                initGridLayer(map) {
                    const colors = map.getStyle().name === "Mapbox Streets" ? {
                        self: '#a87d37',
                        brothers: '#0F32E3',
                        parent: '#303133',
                        uncles: '#188D3F'
                    } : {
                        self: '#EA1ADF',
                        brothers: '#53EEE0',
                        parent: '#F2F6FC',
                        uncles: '#FFE666'
                    }

                    this.addEmptySource(map, currentStickToId)
                    this.addEmptySource(map, selfId)
                    this.addEmptySource(map, othersId)
                    this.addEmptySource(map, centersId)

                    this.addFillLayer(map, othersId, othersId, colors)
                    this.addFillLayer(map, selfId, selfId, colors)

                    this.addLineLayer(map, othersId + "-line", othersId, colors)
                    this.addLineLayer(map, selfId + "-line", selfId, colors)

                    this.addTextLayer(map, centersId, centersId, colors)
                    this.addPointLayer(map, currentStickToId, currentStickToId)

                    this.initGridData(map, true)
                },
                // 初始化网格数据
                initGridData(map, flyTo) {
                    if (this.noParent) {
                        return false
                    }
                    $.get(alluse.bigcenter + '/gis/' + this.dataType + '/list-all/' + this.dataId, res => {
                        if (res.code === 200) {
                            const data = res.data
                            const theSelfFeature = data.self
                            if (theSelfFeature) {
                                this.selfFeature = theSelfFeature
                                const geometry = theSelfFeature.geometry;
                                if (geometry.type === Constants.geojsonTypes.POINT) {
                                    if (flyTo) {
                                        map.flyTo({center: geometry.coordinates, zoom: 13});
                                    }
                                    this.drawStatus = 2
                                } else if (geometry.type === Constants.geojsonTypes.MULTI_POLYGON) {
                                    if (flyTo) {
                                        const bbox = turf.bbox(turf.multiPolygon(geometry.coordinates))
                                        map.fitBounds(bbox, {
                                            animate: false
                                        })
                                    }
                                    map.getSource(selfId).setData(theSelfFeature)
                                    this.drawStatus = 3
                                }
                            } else {
                                if (flyTo) {
                                    const parent = data.others.features.filter(feature => feature.properties.type === 'parent')[0]
                                    const bbox = turf.bbox(turf.multiPolygon(parent.geometry.coordinates))
                                    map.fitBounds(bbox, {
                                        animate: false
                                    })
                                }
                                this.drawStatus = 2
                            }
                            map.getSource(othersId).setData(data.others)
							
							data.centers.features.push({
								type: "Feature",
								properties: {
									id: "1111179",
									name: "问题点11111111111111",
									type: "brothers"
								},
								id: "center-1111179",
								geometry: {
									type: "Point",
									coordinates: [118.18104056242116, 39.6664608]
								}
							})
							
							// data.centers.features.push({
							// 	type: "Feature",
							// 	properties: {
							// 		id: "1111179",
							// 		name: "问题点11111111111111",
							// 		type: "brothers"
							// 	},
							// 	id: "center-1111179",
							// 	geometry: {
							// 		type: "Point",
							// 		coordinates: [118.20002638250722, 39.71781311749278]
							// 	}
							// })
							
							console.log(data.centers);
                            map.getSource(centersId).setData(data.centers)
                            this.otherFeatureCollection = data.others
                            localStorage.setItem('grid-edit-others', JSON.stringify(this.otherFeatureCollection));
                        } else {
                            this.noParent = true
                        }
                    })
                },
                /**
                 * 增加空的数据源
                 * @param map 地图
                 * @param sourceId 数据源ID
                 */
                addEmptySource(map, sourceId) {
                    if (!map.getSource(sourceId)) {
                        map.addSource(sourceId, {
                            "type": "geojson",
                            "data": {
                                type: "FeatureCollection",
                                features: []
                            }
                        })
                    }
                },
                /**
                 * 增加点图层
                 * @param map 地图
                 * @param layerId   图层ID
                 * @param sourceId  数据源ID
                 */
                addPointLayer(map, layerId, sourceId) {
                    map.addLayer({
                        id: layerId + "halo",
                        type: 'circle',
                        minzoom: 6,
                        source: sourceId,
                        paint: {
                            "circle-radius": 5,
                            "circle-color": "#FFF"
                        }
                    })
                    map.addLayer({
                        id: layerId,
                        type: 'circle',
                        minzoom: 6,
                        source: sourceId,
                        paint: {
                            "circle-radius": 3,
                            "circle-color": "#D20C0C",
                        }
                    })
                },
                /**
                 * 增加文本图层
                 * @param map 地图
                 * @param layerId   图层ID
                 * @param sourceId  数据源ID
                 * @param textColor 文本颜色
                 */
                addTextLayer(map, layerId, sourceId, textColor) {
                    map.loadImage('lib/mapbox/img/bus-points-government.png', (error, image) => {
                        if (error) throw error;
                        const img = 'bus-points-government-img';
                        map.addImage(img, image);

                        map.addLayer({
                            id: layerId,
                            type: 'symbol',
                            minzoom: 6,
                            source: sourceId,
                            layout: {
                                'icon-image': img,
                                "icon-size": ["interpolate", ["linear"],
                                    ["zoom"], 12, 0.4, 18, 1.2
                                ],
                                'text-size': ["interpolate", ["linear"],
                                    ["zoom"], 12, 12, 18, 20
                                ],
                                'text-field': ['get', 'name'],
                                'text-justify': 'center',
                                'text-offset': ["interpolate", ["linear"],
                                    ["zoom"], 12, ['literal', [0, 0.9]], 18, ['literal', [0, 1.2]]
                                ],
                                'text-anchor': 'top',
                                'text-letter-spacing': 0.2,
                                'text-max-width': 12
                            },
                            paint: {
                                'text-color': [
                                    'match',
                                    ['get', 'type'],
                                    'self',
                                    textColor.self,
                                    'brothers',
                                    textColor.brothers,
                                    'parent',
                                    textColor.parent,
                                    'uncles',
                                    textColor.uncles,
                                    '#f00'
                                ]
                            }
                        })
                    })
                },
                /**
                 * 增加填充图层
                 * @param map 地图
                 * @param layerId   图层ID
                 * @param sourceId  数据源ID
                 * @param fillColor 填充颜色
                 */
                addFillLayer(map, layerId, sourceId, fillColor) {
                    map.addLayer({
                        'id': layerId,
                        'type': 'fill',
                        'source': sourceId,
                        'minzoom': 6,
                        'paint': {
                            'fill-color': [
                                'match',
                                ['get', 'type'],
                                'self',
                                fillColor.self,
                                'brothers',
                                fillColor.brothers,
                                'parent',
                                fillColor.parent,
                                'uncles',
                                fillColor.uncles,
                                '#f00'
                            ],
                            "fill-opacity": [
                                'match',
                                ['get', 'type'],
                                'parent',
                                0,
                                0.3
                            ]
                        }
                    })
                },
                /**
                 * 增加线图层
                 * @param map 地图
                 * @param layerId     图层ID
                 * @param sourceId    数据源ID
                 * @param lineColor   线颜色
                 * @param isDasharray 是否虚线
                 */
                addLineLayer(map, layerId, sourceId, lineColor, isDasharray) {
                    const config = {
                        'id': layerId,
                        'type': 'line',
                        'source': sourceId,
                        'minzoom': 6,
                        'paint': {
                            'line-color': [
                                'match',
                                ['get', 'type'],
                                'self',
                                lineColor.self,
                                'brothers',
                                lineColor.brothers,
                                'parent',
                                lineColor.parent,
                                'uncles',
                                lineColor.uncles,
                                '#f00'
                            ],
                            'line-width': [
                                'match',
                                ['get', 'type'],
                                'parent',
                                4,
                                2
                            ],
                            "line-opacity": [
                                'match',
                                ['get', 'type'],
                                'parent',
                                1,
                                0.5
                            ]
                        }
                    }
                    map.addLayer(config)
                }
            }
        }
    }

    module.exports = {
        onload
    };
});
